﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CastleDynamicProxyTest
{
    public class WorkAsyncInterceptor : IAsyncInterceptor
    {
        /// <summary>
        /// 同步方法拦截时使用
        /// </summary>
        /// <param name="invocation"></param>
        public void InterceptSynchronous(IInvocation invocation)
        {
            //获取执行信息
            var methodName = invocation.Method.Name;

            Console.WriteLine($"{methodName} 准备执行");

            //调用业务方法
            invocation.Proceed();

            //记录日志
            Console.WriteLine($"{methodName} 已执行");
        }

        /// <summary>
        /// 异步方法返回Task时使用
        /// </summary>
        /// <param name="invocation"></param>
        public void InterceptAsynchronous(IInvocation invocation)
        {
            //获取执行信息
            var methodName = invocation.Method.Name;

            Console.WriteLine($"{methodName} 准备执行");

            //调用业务方法
            invocation.Proceed();
            ((Task)invocation.ReturnValue).GetAwaiter().GetResult();

            //记录日志
            Console.WriteLine($"{methodName} 已执行");
        }

        /// <summary>
        /// 异步方法返回Task<T>时使用
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="invocation"></param>
        public void InterceptAsynchronous<TResult>(IInvocation invocation)
        {
            //调用业务方法
            invocation.ReturnValue = InternalInterceptAsynchronous<TResult>(invocation);
        }

        private async Task<TResult> InternalInterceptAsynchronous<TResult>(IInvocation invocation)
        {
            //获取执行信息
            var methodName = invocation.Method.Name;

            invocation.Proceed();
            var task = (Task<TResult>)invocation.ReturnValue;
            TResult result = await task;

            //记录日志
            Console.WriteLine($"{methodName} 已执行，返回结果：{result}");

            return result;
        }
    }
}
